<?php

namespace app\admin\business;

use \app\common\model\mysql\AdminUser as User;

class AdminUser extends BusBase
{
    protected $userModelObj = null;

    public function __construct()
    {
        $this->userModelObj = new User();
    }

    /**
     * 登录
     * @param  array  $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(array $data)
    {
        $user = $this->getAdminUserByUsername($data['username']);
        if (!$user) {
            return config('status.action_not_found');
        }
        if ($user['password'] != md5($data['password'])) {
            return config('status.password_error');
        }
        $updateData = [
            'last_login_time' => time(),
            'last_login_ip' => $data['ip'],
            'update_time' => time()
        ];
        session('adminUser', $user);
        $res = $this->userModelObj->updateById($user['id'], $updateData);
        return $res;
    }

    /**
     * 获取AdminUser
     * @param $username
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdminUserByUsername($username)
    {
        $user = $this->userModelObj->getAdminUserByUsername($username);
        if (empty($user) || !in_array($user->status, config('status.mysql.table_normal'))) {
            return [];
        }
        return $user->toArray();
    }
}